﻿namespace DataIntegration.Storage.SQL.SQLite
{
    using System.Collections.Generic;
    using System.Data.SQLite;
    using System.Reflection;
    using log4net;

    public class SQLiteDataStoreFactory : SQLDataStoreFactory
    {
        private static readonly ILog Logger = LogManager.GetLogger(MethodBase.GetCurrentMethod().ReflectedType);

        public SQLiteDataStoreFactory(string connectionString, IList<TableDesign> tableDesigns)
            : base(connectionString, tableDesigns)
        {
        }

        public override bool TableExists(string name)
        {
            using (SQLiteConnection connection = new SQLiteConnection(this.ConnectionString))
            {
                string commandText = string.Format("SELECT name FROM sqlite_master WHERE name='{0}'", name);
                SQLiteCommand command = new SQLiteCommand(connection) { CommandText = commandText };
                connection.Open();
                SQLiteDataReader sqliteDataReader = command.ExecuteReader();
                return sqliteDataReader.HasRows;
            }
        }

        public override void DeleteTable(string name)
        {
            this.RunCommand(string.Format("DROP TABLE '{0}'", name));
        }

        public override void RunCommand(string commandText)
        {
            using (SQLiteConnection connection = new SQLiteConnection(this.ConnectionString))
            {
                SQLiteCommand command = new SQLiteCommand(connection) { CommandText = commandText };
                connection.Open();
                command.ExecuteNonQuery();                
            }
        }

        public override IDataStore BuildDataStore()
        {
            return new SQLiteDataStore(this.ConnectionString);
        }
    }
}